package com.yangtao.springbootfreemarker.web.controller.sys;

import com.yangtao.core.exception.ServiceException;
import com.yangtao.core.shiro.util.ShiroUtils;
import com.yangtao.core.web.ResultMsg;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;

@Controller
public class LoginController {

    /**
     * 登录
     */
    @ResponseBody
    @RequestMapping(value = "/sys/login", method = RequestMethod.POST)
    public ResultMsg login(String username, String password) throws IOException {
        try {
            Subject subject = ShiroUtils.getSubject();
            UsernamePasswordToken token = new UsernamePasswordToken(username, password);
            subject.login(token);
        } catch (UnknownAccountException e) {
            throw new ServiceException("账号或密码不正确");
        } catch (IncorrectCredentialsException e) {
            throw new ServiceException("账号或密码不正确");
        } catch (LockedAccountException e) {
            throw new ServiceException("账号已被锁定,请联系管理员");
        } catch (AuthenticationException e) {
            throw new ServiceException("账户验证失败");
        }
        // 返回成功信息
        return ResultMsg.buildSuccessMsg();
    }
}
